/**
 * Created by sam on 16-10-19.
 */
var cheerio = require('cheerio');
var utils = require('./utils');
var dao = require('./dao');
var common = require("../conf/common");

//替换所有
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};


function loadAzRank(obj, page, ep) {
   var url = common.getDomain()+"/s/ref=nb_sb_noss?url=search-alias%3D" + obj.category + "&field-keywords=" + obj.keyword.replaceAll(" ", "+") + "&page=" + page;
    var source = common.getSource();
    utils.getc(url,obj.num,function (html) {
        if (html == 'timeout') {
            console.log("Thread["+obj.num+"] keyword:" + obj.keyword + ",page:" + page);
            ep.emit("sleep", obj);
        } else {
            var $ = cheerio.load(html);

            if($("#captchacharacters").length>0){
                console.log("Thread["+obj.num+"] .... robot ....");
                ep.emit("sleep", obj);
            }else {

                var txt = $("#s-result-count").text();
                var rank = parseInt(txt.split(" of")[0].split("-")[0]);

                var params = [];

                $(".s-result-item ").each(function () {
                    var sponsored = $("h5", $(this)).length;
                    if (sponsored == 0) {

                        var asin = $(this).attr("data-asin");
                        var title = $("h2", $(this)).attr("data-attribute");
                        var price = $("div.a-row.a-spacing-none > a > span", $(this)).attr("aria-label");

                        var is_pro_price = $("div.a-spacing-none > .a-letter-space", $(this)).length > 1 ? 1 : 0;
                        var img = $("img", $(this)).attr('src');
                        var brand = $(".a-color-secondary", $(this)).eq(1).text();

                        var comm = $("span[name='" + asin + "']", $(this)).next().text().replaceAll(",", "");
                        var grade = $(".a-icon-star >span", $(this)).last().text().replace(" out of 5 stars", "");

                        var data = {
                            fetchTime: common.getFetchTime(),
                            asin: asin,
                            title: title,
                            source: source,
                            price: price,
                            is_pro_price: is_pro_price,
                            img: img,
                            brand: brand,
                            comm: comm,
                            grade: grade,
                            rank: rank,
                            page: page,
                            index: rank++,
                            category: obj.category,
                            keyword: obj.keyword,
                        };

                        /*console.log("=================================================");
                         console.log("");
                         console.log(data);*/

                        //dao.saveRank(data);
                        //dao.saveHotkeyRank(data);
                        params.push([data.fetchTime,data.asin, data.page, data.index, data.category, data.keyword, data.img, data.rank, data.price||'', data.grade || 0,
                            data.comm || 0, data.title, data.is_pro_price, data.brand])
                    }
                });

                var sql = "insert into t_az"+source+"_hot_key_ranking(fetch_time,asin,page_num,page_set,category_name,keyword,";
                sql += "img_url,rank,pro_price,pro_grade,comment_total_number,pro_name,is_promotion_price,brand_name)";
                sql += "values(?,?,?,?,?,? ,?,?,?,?,?,?,?,?)";

                dao.execTrans(sql,params,function (err) {
                        if(err) console.log(err + "")
                        ep.emit('next_word', obj);
                });



            }
        }
    })
}

function loadAzAbsrRank(obj,ep) {
    var source = common.getSource();
    utils.getc(obj.url+"&ajax=1",obj.num,function (html) {
        if (html == 'timeout') {
            ep.emit("sleep",obj);
        } else {

            var $ = cheerio.load(html);

            $(".zg_itemImmersion").each(function () {
                var rank = $(".zg_rankNumber", $(this)).text().trim().replace(".", "");
                var title = $(".a-section .a-spacing-mini ", $(this)).next().attr("title");
                var img = $(".a-section .a-spacing-mini > img", $(this)).attr("src");
                var grade = $(".a-icon-star > span ", $(this)).text().replace(" out of 5 stars", "");
                var comm = $(".a-size-small .a-link-normal", $(this)).text().replaceAll(",","");
                var price = $(".a-color-price ", $(this)).text();
                var href = $(".a-link-normal", $(this)).first().attr("href");
                var metadata = $(".p13n-asin ", $(this)).attr("data-p13n-asin-metadata");
                var asin = JSON.parse(metadata).asin;

                //console.log("rank:" + rank + ",grade:" + grade + ",comm:" + comm + ",price:" + price + ",asin:" + asin);
                /* console.log("title:" + title);
                console.log("img:" + img);
                console.log("href:" + href);*/

                var data = {
                    num:obj.num,
                    url:obj.url,
                    source:source,
                    rank:rank,
                    grade:grade,
                    comm:comm,
                    price:price,
                    asin:asin,
                    category:obj.category,
                    pro_url:common.getDomain()+href,
                }
                dao.saveAbsrRank(data);
            });

            ep.emit('next_word', obj);
        }
    })
}


module.exports.loadAzRank = loadAzRank;
module.exports.loadAzAbsrRank = loadAzAbsrRank;
